<template>
  <div class="cmt-container">
    <br />
    <h3>发表评论</h3>
    <hr />
    <textarea placeholder="请输入评论内容" maxlength="120" v-model="msg"></textarea>
    <mt-button type="primary" size="large" @click="postComments">发表评论</mt-button>
    <div class="cmt-list">
      <div class="cmt-item" v-for="(item,i) in comments" :key="item.id">
        <div
          class="cmt-title"
        >第{{i+1}}楼&nbsp;&nbsp;用户:{{ item.user_name }}&nbsp;&nbsp;发表时间:{{ item.add_time | dateFormat }}</div>
        <div class="cmt-body">{{ item.content === 'undefined' ? '此用户很懒，嘛都没说': item.content }}</div>
      </div>
    </div>
    <mt-button type="danger" size="large" plain @click="getMore">加载更多</mt-button>
  </div>
</template>

<script>
import {Toast} from 'mint-ui'
export default {
  data() {
    return {
      pageIndex: 1, //页码
      comments: [], //评论数据，获取多组数据应用concat()数组拼接方法
      msg:""  //添加评论内容
    };
  },
  props: ["id"], //从父组件newsinfo那传过来的id值
  created() {
    this.getComments();
  },
  methods: {
    getComments() {
      this.$axios
        .get("api/getcomments/" + this.id + "?pageindex=" + this.pageIndex)
        .then(Response => {
          //this.comments = Response.data.message;
          // 每当加载更多新评论数据的时候，不要把老数据清空覆盖，而是应该以老数据，拼接上新数据
          this.comments = this.comments.concat(Response.data.message);
        })
        .catch(error => {
          console.lig("获取评论失败" + error);
        });
    },
    getMore() {
      // 加载更多
      this.pageIndex++;
      this.getComments();
    },
    postComments(){
      if(this.msg.trim().length === 0){   //trim():去掉字符串首尾的空格
        return Toast("评论内容不能为空")
      }

      this.$axios
      .post("api/postcomment/" + this.$route.params.id, {content: this.msg.trim()})
      .then(Response=>{
        //方法1：数据传到后台再重新调用getComments()获取新数据。缺点：会重新刷新评论栏，页面高度会跳跃，且多发了次请求
        // this.pageIndex = 1;
        // this.comments = []; //因为getComments()方法里获取的数据存储是用的拼接，会将新数据拼接在后面，所以要把新评论展示在第一条，需先清空原来的老数据
        // this.getComments();

        //方法2：数据传到后台即可，手动在前端创建这条数据对象，添加到comments数组头部。优点：流畅
        var cmt = {
              user_name: "匿名用户",
              add_time: Date.now(),
              content: this.msg.trim()
            };
        this.comments.unshift(cmt);
        Toast("发表成功");
        this.msg = "";
      })
    }
  }
};
</script>

<style lang="scss" scoped>
.cmt-container textarea {
  font-size: 14px;
  height: 100px;
  margin: 0;
}
.cmt-list {
  margin-top: 10px;
}
.cmt-title {
  line-height: 30px;
  background-color: #ccc;
}
.cmt-body {
  line-height: 40px;
  text-indent: 2em;
}
</style>

